/**
 * unPlarer-Youtube 0.8.0 
 *
 * @author Alvaro Lopez, Juan Baquero
 * 
 * http://code.google.com/p/unplayer-youtube/
 **/

package unplayer.youtubeplayer.util;

import processing.core.PApplet;

public class LogicalCache extends Thread {

	public LogicalCache(UrlStream call, PApplet papplet, String file)
	{
		parent=papplet;
		caller=call;
		filep=file;
		broke=false;
	}
	
	public void run()
	{
		byte[] bytes = parent.loadBytes(filep);
		long initTime = System.currentTimeMillis();
		boolean error = false;
		
		while(true)
		{
			if(broke) return;
			
			if(System.currentTimeMillis()-initTime>=maxTime)
			{
				error=true;
				break;
			}
			
			bytes = parent.loadBytes(filep);
			if(bytes!=null && bytes.length>=minSize)
				break;
			
			try {
				Thread.sleep(50);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		if(error)
		{
			if(bytes.length>0) caller.loadResults(UrlStream.LAZY_CONNECTION);
			else caller.loadResults(UrlStream.NO_CONNECTION);
		}else
		{
			caller.loadResults(UrlStream.OK);
		}
	}
	
	private PApplet parent;
	private String filep;
	private UrlStream caller;
	public boolean broke;
	
	int minSize = 100000; // CUANDO CARGUE 100Kb
	long maxTime = 60000; //CUANDO PASEN 60 SEGUNDOS ABORTA
	
}
